package com.hzhh123.crypto.exception;

import com.hzhh123.crypto.entity.Result;
import com.hzhh123.crypto.entity.ResultBuilder;

import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;
import java.util.stream.Collectors;

@RestControllerAdvice
public class CryptoGlobalExceptionAdvice implements ResultBuilder {
    @ExceptionHandler(value = BindException.class)
    public ResponseEntity<Result<?>> bindExceptionHandler(BindException ex) {
        ex.printStackTrace();
        // 获取所有错误信息，拼接
        List<FieldError> fieldErrors = ex.getBindingResult().getFieldErrors();
        String errorMsg = fieldErrors.stream()
                .map(fieldError -> fieldError.getField() + ":" + fieldError.getDefaultMessage())
                .collect(Collectors.joining(","));
        // 返回统一处理类
        return badRequest(errorMsg);
    }

    @ExceptionHandler(DecryptException.class)
    public ResponseEntity<Result<?>> DecryptException(DecryptException e) {
        return badRequest(e.getMessage());
    }

    @ExceptionHandler(EncryptException.class)
    public ResponseEntity<Result<?>> EncryptException(EncryptException e) {
        return error(e.getMessage());
    }

    @ExceptionHandler(ParamException.class)
    public ResponseEntity<Result<?>> ParamException(ParamException e) {
        return error(e.getMessage());
    }

    @ExceptionHandler(Exception.class)
    public ResponseEntity<Result<?>> Exception(Exception e) {
        return error(e.getMessage());
    }
}
